package com.jfinal.ext.plugin.shiro;

/**
 * @author fupan
 * @description 基于角色的访问控制器
 * @create 2017-08-24 16:44
 **/

import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;

public class JdbcRoleAuthzHandler extends AbstractAuthzHandler {
    private final String[] jdbcPermissions;

    public JdbcRoleAuthzHandler(String[] jdbcPermissions) {
        this.jdbcPermissions = jdbcPermissions;
    }

    @Override
    public void assertAuthorized() throws AuthorizationException {
        Subject subject = getSubject();
        //数据库权限
        if (jdbcPermissions.length == 1) {
            subject.checkRole(jdbcPermissions[0]);
            return;
        } else {
            // Avoid processing exceptions unnecessarily - "delay" throwing the exception by calling hasRole first
            boolean hasAtLeastOneRole = false;
            for (String role : jdbcPermissions) if (subject.hasRole(role)) hasAtLeastOneRole = true;
            // Cause the exception if none of the role match, note that the exception message will be a bit misleading
            if (!hasAtLeastOneRole) subject.checkRole(jdbcPermissions[0]);
            return;
        }
    }
}

